import React, { useState, useEffect } from 'react';
import { getDoctorAppointments, updateDoctorAppointmentStatus } from '../../services/appointmentService';
import './AppointmentList.css';

const AppointmentList = () => {
  const [appointments, setAppointments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [statusFilter, setStatusFilter] = useState('ALL');
  
  // 获取医生的预约列表
  useEffect(() => {
    const fetchAppointments = async () => {
      try {
        setLoading(true);
        const data = await getDoctorAppointments();
        setAppointments(data);
        setError(null);
      } catch (err) {
        setError('获取预约列表失败，请稍后重试');
        console.error('获取预约列表错误:', err);
      } finally {
        setLoading(false);
      }
    };
    
    fetchAppointments();
  }, []);
  
  // 更新预约状态
  const handleStatusChange = async (appointmentId, newStatus) => {
    try {
      await updateDoctorAppointmentStatus(appointmentId, newStatus);
      // 更新本地状态
      setAppointments(appointments.map(appointment => 
        appointment.id === appointmentId 
          ? { ...appointment, status: newStatus } 
          : appointment
      ));
    } catch (err) {
      console.error('更新预约状态错误:', err);
      alert('更新预约状态失败，请稍后重试');
    }
  };
  
  // 按状态筛选预约
  const filteredAppointments = statusFilter === 'ALL'
    ? appointments
    : appointments.filter(appointment => appointment.status === statusFilter);
    
  // 获取状态对应的中文名称
  const getStatusName = (status) => {
    switch (status) {
      case 'PENDING': return '待处理';
      case 'CONFIRMED': return '已确认';
      case 'CANCELED': return '已取消';
      case 'COMPLETED': return '已完成';
      default: return status;
    }
  };
  
  // 获取状态对应的CSS类名
  const getStatusClass = (status) => {
    switch (status) {
      case 'PENDING': return 'status-pending';
      case 'CONFIRMED': return 'status-confirmed';
      case 'CANCELED': return 'status-canceled';
      case 'COMPLETED': return 'status-completed';
      default: return '';
    }
  };

  return (
    <div className="appointment-list-container">
      <h2 className="appointment-list-title">我的预约列表</h2>
      
      {/* 状态筛选 */}
      <div className="filter-container">
        <label>按状态筛选：</label>
        <select 
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="status-filter"
        >
          <option value="ALL">所有状态</option>
          <option value="PENDING">待处理</option>
          <option value="CONFIRMED">已确认</option>
          <option value="CANCELED">已取消</option>
          <option value="COMPLETED">已完成</option>
        </select>
      </div>
      
      {/* 加载中提示 */}
      {loading && <div className="loading-message">加载中，请稍候...</div>}
      
      {/* 错误提示 */}
      {error && <div className="error-message">{error}</div>}
      
      {/* 无预约提示 */}
      {!loading && !error && filteredAppointments.length === 0 && (
        <div className="no-appointments-message">
          {statusFilter === 'ALL' ? '暂无预约记录' : `暂无${getStatusName(statusFilter)}状态的预约`}
        </div>
      )}
      
      {/* 预约列表 */}
      {!loading && !error && filteredAppointments.length > 0 && (
        <div className="appointment-table-container">
          <table className="appointment-table">
            <thead>
              <tr>
                <th>预约ID</th>
                <th>患者姓名</th>
                <th>预约日期</th>
                <th>预约时间</th>
                <th>科室</th>
                <th>原因</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {filteredAppointments.map(appointment => (
                <tr key={appointment.id}>
                  <td>{appointment.id}</td>
                  <td>{appointment.patientName}</td>
                  <td>{appointment.appointmentDate}</td>
                  <td>{appointment.appointmentTime}</td>
                  <td>{appointment.departmentName}</td>
                  <td>
                    <div className="reason-cell" title={appointment.reason}>
                      {appointment.reason?.length > 20 
                        ? `${appointment.reason.substring(0, 20)}...`
                        : appointment.reason}
                    </div>
                  </td>
                  <td>
                    <span className={`status-badge ${getStatusClass(appointment.status)}`}>
                      {getStatusName(appointment.status)}
                    </span>
                  </td>
                  <td>
                    {appointment.status === 'PENDING' && (
                      <div className="action-buttons">
                        <button 
                          className="confirm-button"
                          onClick={() => handleStatusChange(appointment.id, 'CONFIRMED')}
                        >
                          确认
                        </button>
                        <button 
                          className="cancel-button"
                          onClick={() => handleStatusChange(appointment.id, 'CANCELED')}
                        >
                          取消
                        </button>
                      </div>
                    )}
                    {appointment.status === 'CONFIRMED' && (
                      <div className="action-buttons">
                        <button 
                          className="complete-button"
                          onClick={() => handleStatusChange(appointment.id, 'COMPLETED')}
                        >
                          完成
                        </button>
                        <button 
                          className="cancel-button"
                          onClick={() => handleStatusChange(appointment.id, 'CANCELED')}
                        >
                          取消
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

export default AppointmentList; 